package com.smcdd.cdb.dbo.cdb_dbo.network.factory;

import android.net.ParseException;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.smcdd.cdb.dbo.cdb_dbo.network.BaseErrorBean;
import com.smcdd.cdb.dbo.cdb_dbo.service.exception.ApiException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;


/**
 * Created by Jeremylee on 2017/6/5.
 */

public class FactoryException {


    public static ApiException analysisException(Throwable e){
        ApiException apiError = new ApiException(e);
        if (e instanceof HttpException){
            HttpException httpException = (HttpException) e;
            if (httpException.response() != null && httpException.response().errorBody() != null){
                try {
                    String bodyStr = httpException.response().errorBody().toString();
                    Gson gson = new Gson();
                    BaseErrorBean bean = gson.fromJson(bodyStr,BaseErrorBean.class);
                    if (bean != null) {
                        apiError.setCode(bean.getErrorCode());
                        apiError.setMessage(bean.getErrorDesc());
                    } else {
//                        apiError.setCode(CodeException.HTTP_ERROR);
//                        apiError.setMessage(HttpException_MSG);
                    }
                } catch (JsonSyntaxException e1) {
//                    apiError.setCode(CodeException.HTTP_ERROR);
//                    apiError.setMessage(HttpException_MSG);
                }
            }
        }else if (e instanceof ConnectException || e instanceof SocketTimeoutException){
            /*链接异常*/
        }else if (e instanceof JSONException || e instanceof ParseException ||e instanceof JsonSyntaxException){
             /*fastjson解析异常e instanceof JSONPathException || */

        }else if (e instanceof UnknownHostException){
            /*无法解析该域名异常*/

        }else {
            /*未知异常*/

        }

        return apiError;
    }
}
